package com.chatserver.client.handlers;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import com.chatserver.client.gui.Frame;

/**
 * This manages connection from and to the main chat server.
 * @author Dohmen
 */
public class ConnectionHandler {
	public static Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;
	String username;
	String password;
	public static int OPTION;
	public void run() {
		try {
			//1. creating a socket to connect to the server
			requestSocket = new Socket("localhost", 43594);
			System.out.println("Connected to localhost in port 43594");
			//2. get Input and Output streams
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			//3: Communicating with the server
			do {
				try {
					message = (String)in.readObject();
					System.out.println("[ChatServer] " + message);
					sendMessage("[Client] ping");
					message = "pong";
					sendMessage(message);
					/*sendInt(1);
					if (requestSocket != null) {
						OPTION = in.read();
						System.out.println("Option: " + OPTION);
					}*/
					//System.out.println("Connection option: " + OPTION);
				} catch(ClassNotFoundException classNot) {
					System.err.println("data received in unknown format");
				}
			}while(!message.equals("bye"));
		} catch(UnknownHostException unknownHost) {
			System.err.println("You are trying to connect to an unknown host!");
		} catch(IOException ioException) {
			ioException.printStackTrace();
		}
		
		finally {
			//4: Closing connection
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch(IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}
	
	void sendInt(int o) {
		try {
			out.write(o);
			out.flush();
			System.out.println("Option: " + o);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	public void sendMessage(String msg)
	{
		try{
			out.writeObject(msg);
			out.flush();
			System.out.println("client>" + msg);
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
}
